package top.yuhaitao.core.miniprogram;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yuhaitao.core.miniprogram.model.SessionKey;
import top.yuhaitao.core.miniprogram.request.model.CodeModel;
import top.yuhaitao.core.util.OkhttpUtil;
import top.yuhaitao.core.util.RedisUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * index
 *
 * @author ht.yu 75751845@qq.com
 * @date 2019-1-25 18:45:03
 */

@RestController
@RequestMapping("/miniProgramController")
public class MiniProgramController {

    private static final String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
    private static final String appid = "wxf74108bdf12da00b";
    private static final String secret = "5c737152fcfe02ce6a798b77d3717278";

    private static final String USER_REDIS_SESSION = "user_redis_session";

    private Logger log = LoggerFactory.getLogger(MiniProgramController.class);

    @Resource
    private RedisUtil redisUtil;


    @RequestMapping("/code2session")
    public String code2session(@RequestBody CodeModel codeModel) throws IOException {
        if (codeModel == null || StringUtils.isEmpty(codeModel.getCode())) {
            throw new RuntimeException("code为空");
        }
        String url = loginUrl.replace("APPID", appid).replace("SECRET", secret).replace("JSCODE", codeModel.getCode());
        String json = OkhttpUtil.httpGet(url);
        SessionKey sessionKey = new Gson().fromJson(json, SessionKey.class);
        redisUtil.set(USER_REDIS_SESSION + sessionKey.getOpenid(), json);
        return "ok";
    }


    @RequestMapping("/getJson")
    public List<Map<String, Object>> getJson(Long id) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        Map<String, Object> map3 = new HashMap<>();
        list.add(map1);
        list.add(map2);
        list.add(map3);
        Map<String, Object> map;
        for (int i = 0; i < 3; i++) {
            map = list.get(i);
            map.put("img", "/images/pro_0" + (i + 1) + ".jpg");
            map.put("title", "标题" + (i + 1));
            map.put("shortDesc", "内容内容内容内容内容内容内容" + (i + 1));
        }

        return list;
    }
}
